package com.cloud.common.controller;

import com.cloud.common.bean.ResultInfo;
import com.cloud.common.bean.SessionInfo;
import com.cloud.common.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 访问令牌
 *
 * @author fengwenjin
 */
@Slf4j
@RestController
@ConditionalOnMissingClass("com.cloud.gateway.bean.GatewayInfo")
public class TokenController {
    /**
     * 创建令牌
     *
     * @param sessionInfo
     */
    @PostMapping("/token/create")
    public ResultInfo<String> create(@Valid @RequestBody SessionInfo sessionInfo) {
        String token = TokenUtils.build(sessionInfo.getAppName(), sessionInfo.getUserId(), sessionInfo.getSecret());
        return ResultInfo.success().setData(token);
    }

    /**
     * 解析令牌
     *
     * @param token
     */
    @PostMapping("/token/parse")
    public ResultInfo<TokenUtils.AppUser> parse(String token) {
        TokenUtils.AppUser user = TokenUtils.parse(token);
        return ResultInfo.success().setData(user);
    }
}
